package com.dict;

import java.net.URL;
import java.util.Calendar;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;



import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.dict.receivers.AlarmReceiver;
import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.error.EasyFacebookError;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DictionaryActivity extends Activity implements OnClickListener,LoginListener{

	/** Create Object For SiteList Class */
	XMLList list = null;
	public EditText et;
	private TextView tv;
	private Button search;
	private FBLoginManager fbmanager;
	private AlertDialog.Builder build;
	private AlertDialog alert;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		et=(EditText) findViewById(R.id.edit);
		tv=(TextView) findViewById(R.id.dict);
		search = (Button)findViewById(R.id.ok);
		search.setOnClickListener(this);

		//startService(new Intent(this,NotificationService.class));

		Bundle b = getIntent().getExtras();
		if(b!=null){
			String word = b.getString("word");
			et.setText(word);
			NotificationManager nm = (NotificationManager) 
					getSystemService(NOTIFICATION_SERVICE);

			//---cancel the notification---
			nm.cancel(getIntent().getExtras().getInt("NotifID"));
		}

		setAlarm();
	}
	private void setAlarm(){

		AlarmManager am=(AlarmManager) getSystemService(ALARM_SERVICE);
		Calendar cal = Calendar.getInstance();
		//am.setRepeating(type, triggerAtTime, interval, operation)

		//This will fire the alarm every minute
		cal.add(Calendar.SECOND, 5);

		//System.out.println("FIRE TIME: " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));

		Intent in = new Intent(this, AlarmReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);

		//am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2*60*1000, pi);

		Log.d("Dictionary", "Alarms Set ");
	}
	@Override
	public void onResume(){
		super.onResume();


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}



	@Override
	public void onClick(View v) {


		if(v.getId()==R.id.ok){			
			tv.setText("");
			try {

				/** Handling XML */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();

				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(
						"http://api-pub.dictionary.com/v001?vid=aqjxh56ojb1b2yxervp0dzx3he1kmp3xfnuws1lccn&q="+et.getText().toString());

				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				XMLHandler handler = new XMLHandler();
				xr.setContentHandler(handler);
				xr.parse(new InputSource(sourceUrl.openStream()));

			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}

			/** Get result from XMLHandler list Object */
			list = (XMLList)XMLHandler.list;




			String[] def =new  String[list.getDef().size()];
			String pron;
			String display;

			String[] partsOfSpeech = new  String[list.getPartsOfSpeech().size()];
			pron="<i>pron</i>"+"   "+list.getPron().toString();
			display="<h4>"+list.getDefSize().toString()+"</h4>";
			CharSequence pronunciation=Html.fromHtml(pron);
			CharSequence dis=Html.fromHtml(display);
			CharSequence pos;
			CharSequence definition;
			if(list.getPartsOfSpeech().size()==0)
			{
				tv.setText(list.getResult().toString());
			}
			else
			{
				tv.setText(dis);
				tv.append("\n");
				tv.append(pronunciation);
				for (int i = 0; i < list.getPartsOfSpeech().size(); i++) {


					partsOfSpeech[i] ="<i>"+list.getPartsOfSpeech().get(i).toString()+"</i>";
					pos= Html.fromHtml(partsOfSpeech[i].toString());
					def[i] = "<i>def</i>"+"   "+"<b>"+list.getDef().get(i).toString()+"</b>";
					definition= Html.fromHtml(def[i].toString());

					//tv.setText(et.getText().toString());
					tv.append("\n\n");
					tv.append(pos);
					tv.append("\n\n");
					tv.append(definition);
					tv.append("\n");
				}
			}

		}
	}


	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		String msg=tv.getText().toString();
		switch (item.getItemId()) {
		case R.id.sms:
			sentSMS();
			return true;
		case R.id.fb:
			if(msg.equals("No results found")||msg.length()==0){
				Toast.makeText(getBaseContext(), "No results to send a message", 
						Toast.LENGTH_SHORT).show();
			}
			else
			{
				setStatus();
			}

		}
		return super.onMenuItemSelected(featureId, item);
	}


	private void setStatus(){
		build=new AlertDialog.Builder(this);
		build.setMessage("Do you want to update the status?");
		build.setCancelable(false);
		build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				shareFacebook();
			}
		});

		build.setNegativeButton("No", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		alert=build.create();
		alert.show();
	}
	private void shareFacebook(){
		String permissions[] = {"read_stream","publish_stream","offline_access"};		

		fbmanager = new FBLoginManager(this,R.layout.main,"305627786133126",permissions);

		if (fbmanager.existsSavedFacebook()) {
			fbmanager.loadFacebook();
		} else {

			fbmanager.login();
		}
	}

	private void sentSMS() {

		String msg=tv.getText().toString();
		if(msg.equals("No results found")||msg.length()==0){
			Toast.makeText(getBaseContext(), "No results to send a message", 
					Toast.LENGTH_SHORT).show();
		}
		else
		{
			Intent sendIntent = new Intent(Intent.ACTION_VIEW);
			sendIntent.putExtra("sms_body", msg); 
			sendIntent.setType("vnd.android-dir/mms-sms");
			startActivity(sendIntent);
		}

	}




	@Override
	public void loginSuccess(Facebook facebook) {
		GraphApi graphApi= new GraphApi(facebook);

		String response = "";

		try {
			response = graphApi.setStatus("Word for the day - "+"\n"+tv.getText().toString());
			Toast.makeText(this, "Updated successfully", Toast.LENGTH_LONG).show();
		} catch (EasyFacebookError e) {
			e.toString();
		}

	}


	@Override
	public void logoutSuccess() {
		fbmanager.displayToast("Logout success!");		
	}


	@Override
	public void loginFail() {
		fbmanager.displayToast("Login failed!");	
	}
}



